package com.flycent.hqhs.ui;


import java.lang.ref.WeakReference;
import java.util.List;

import net.tsz.afinal.FinalActivity;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.flycent.hqhs.App;
import com.flycent.hqhs.R;
import com.flycent.hqhs.adapter.MyGridAdapter;
import com.flycent.hqhs.bean.Expert;
import com.flycent.hqhs.bean.PageEntity;
import com.flycent.hqhs.http.WebClient;
import com.flycent.hqhs.http.WebException;
import com.flycent.hqhs.ui.view.AbsViewHolderAdapter;
import com.flycent.hqhs.ui.view.RefreshViewLoadMoreProxy;
import com.flycent.hqhs.ui.view.RefreshViewLoadMoreProxy.OnLoadDataActionListener;
import com.flycent.hqhs.util.DateTimeUtil;
import com.flycent.hqhs.util.ImageUtil;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.nostra13.universalimageloader.core.ImageLoader;

/**
 *  达人动态
 * @author fbl
 */
public class ExpertActivity extends SimpleTitleBarActivity implements OnLoadDataActionListener{

	private PullToRefreshListView mRefreshListView;
	private RefreshViewLoadMoreProxy mLoadMoreProxy;

	//	private List<MyBean> myBeans = new ArrayList<MyBean>();
	private ExportAdapter mAdapter;
	private List<Expert> mExperts;
	private int nowPage = 1;
	private RelativeLayout mEmptyRelat;
	
	private  Handler mHandler = new MyHandler(this);

	@Override
	protected void onCreate(Bundle arg0) {
		super.onCreate(arg0);
		setContentView(R.layout.activity_expert);
		FinalActivity.initInjectedView(this);
		getTitleBar().setTitle(R.string.main_expert);
		mEmptyRelat = (RelativeLayout) findViewById(R.id.expert_empty_relat);

		mRefreshListView = (PullToRefreshListView) findViewById(R.id.expert_list);
		mRefreshListView.setEmptyView(mEmptyRelat);
		mRefreshListView.getRefreshableView().setDividerHeight(getResources().getDimensionPixelOffset(R.dimen.dimen_10dp));
		mRefreshListView.getRefreshableView().setSelector(new ColorDrawable(Color.TRANSPARENT));
		mAdapter = new ExportAdapter(this, R.layout.item_export_list_detail);
		mRefreshListView.setAdapter(mAdapter);

		mLoadMoreProxy = new RefreshViewLoadMoreProxy(mRefreshListView, Mode.BOTH,0,0);
		mLoadMoreProxy.setOnLoadDataActionListener(this);
		mLoadMoreProxy.refreshing();

	}

	@Override
	public void onRefresh(int page) {
		updateExpertList(1, true);
	}

	@Override
	public void onLoadMore(int page) {
		nowPage++;
		updateExpertList(nowPage, false);
	}


	private void updateExpertList(final int pageNum,final boolean isRefresh){
//		mLoadMoreProxy.loadDataActionComplete(false);

		new Thread(){
			public void run() {
				try{
					WebClient client = WebClient.getInstance(ExpertActivity.this);
					PageEntity<Expert> entry = client.sunSingle(pageNum, 10, "", "desc");
					int totlePage = entry.getTotalPages();
					mExperts = entry.getContent();
					if(pageNum > totlePage){
						App.showShortToast(R.string.the_end_page);
						mExperts = null;
					}
				} catch (WebException e) {
					if (WebException.TYPE_SERVER_RETURN_NULL.equals(e.getStatusCode()))
						mExperts = null;
					else
						e.printStackTrace();
				}catch (Exception e) {
					App.showShortToast(R.string.unknownerror);
				}

				if(isRefresh)
					mHandler.sendEmptyMessage(0);	
				else
					mHandler.sendEmptyMessage(1);
			};
		}.start();

//		mLoadMoreProxy.loadDataActionComplete(true);
	}
	
	@SuppressLint("HandlerLeak") 
	private class MyHandler extends Handler{
		
		private final WeakReference<Activity> mActivity;
		
		public MyHandler(Activity activity){
			mActivity = new WeakReference<Activity>(activity); 
		}
		
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			if( mActivity.get() != null ){
				switch (msg.what) {
				case 0:
					mAdapter.update(mExperts);
					mRefreshListView.onRefreshComplete();
					break;
				case 1:
					mAdapter.append(mExperts);
					mRefreshListView.onRefreshComplete();
					break;

				default:
					break;
				}
			}
		}
		
		
	}
	

	public class ExportAdapter extends AbsViewHolderAdapter<Expert>{

		public ExportAdapter(Context context, int layoutRes) {
			super(context, layoutRes);
		}

		@Override
		protected void bindData(int pos, final Expert itemData) {

			ImageView mFaceImg = getViewFromHolder(R.id.avator);
			TextView mNameText = getViewFromHolder(R.id.name);
			TextView mContentText = getViewFromHolder(R.id.content);
			TextView mTimeText = getViewFromHolder(R.id.time);
			GridView mGridView = getViewFromHolder(R.id.gridView);
			

			ImageLoader.getInstance().displayImage(itemData.getMember().getImage(), mFaceImg);
			mNameText.setText(itemData.getMember().getUsername());
			mContentText.setText(itemData.getContent());
			mTimeText.setText(DateTimeUtil.getDateTime(itemData.getCreateDate()));

			if(itemData.getReviewImages() != null && itemData.getReviewImages().size() > 0 ){
				final String [] ss = new String[itemData.getReviewImages().size()]; 
				for (int i = 0; i < itemData.getReviewImages().size(); i++) {
					ss[i] = itemData.getReviewImages().get(i).getUrl();
				}
				
				mGridView.setVisibility(View.VISIBLE);
				mGridView.setAdapter(new MyGridAdapter(ss,ExpertActivity.this));
				mGridView.setOnItemClickListener(new OnItemClickListener() {

					@Override
					public void onItemClick(AdapterView<?> arg0, View arg1,
							int position, long arg3) {

						ImageUtil.imageBrower(ExpertActivity.this,position,ss);
					}
				});

			}else {
				mGridView.setVisibility(View.GONE);
			}

		}

	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		mHandler.removeCallbacksAndMessages(null); //清除所有的线程
	}
	


}
